package com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.topic;

import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerDynamicComponent;
import com.kaiwukj.android.ufamily.di.module.DynamicModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.HomeEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.CommentParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.CommentReplyParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.DynamicListParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommentResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DynamicResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.DynamicContract;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.detail.DynamicPresenter;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.report.ReportCardFragment;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.home.DynamicAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.widget.SpaceItemDecoration;
import com.kaiwukj.android.ufamily.utils.DialogUtilsKt;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;

public class DynamicFragment extends BaseMvpFragment<DynamicPresenter> implements DynamicContract.View {

    //@BindView(R.id.refresh_layout)
    // SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_list)
    RecyclerView recyclerView;

    private DynamicAdapter mAdapter;
    private int topicId;
    private int flag;

    private BottomSheetDialog commentDialog;//评论dialog(底部弹出)
    private EditText etCommentInput;
    private MaterialDialog mDynamicEventDialog;

    private int pageSize = 12;
    private int page = 1;

    private boolean isLoadingMore = false;
    private boolean isEnd = false;

    private boolean isNeedRefresh = true;

    private int commentDynamicId = -1;

    private int eventPos = -1;

    public static DynamicFragment newInstance(int flag, int topicId) {
        Bundle bundle = new Bundle();
        bundle.putInt("flag", flag);
        bundle.putInt("topicId", topicId);
        DynamicFragment fragment = new DynamicFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        super.setupFragmentComponent(appComponent);
        DaggerDynamicComponent.builder()
                .appComponent(appComponent)
                .dynamicModule(new DynamicModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.widget_list_base;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            topicId = bundle.getInt("topicId");
            flag = bundle.getInt("flag");
        }
    }

    @Override
    protected void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new SpaceItemDecoration(10));
        mAdapter = new DynamicAdapter(new ArrayList<>());
        mAdapter.setIndex();
        recyclerView.setAdapter(mAdapter);
        View emptyView = View.inflate(getContext(), R.layout.empty_view_common_container, null);
        mAdapter.setEmptyView(emptyView);

        View footerView = View.inflate(getContext(), R.layout.item_common_footer, null);
        //footerView.setText("没有更多数据了~");
        mAdapter.setFooterView(footerView);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isEnd) {
                    return;
                }

                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (linearLayoutManager == null) return;
                int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                int totalItemCount = linearLayoutManager.getItemCount();
                if (lastVisibleItem >= totalItemCount - 2 && dy > 0) {  //还剩2个Item时加载更多
                    if (!isLoadingMore) {
                        isLoadingMore = true;
                        ++page;
                        loadData(false);
                    }
                }
            }
        });

        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            eventPos = position;
            switch (view.getId()) {
                case R.id.btn_attention:
                    DynamicResult item = mAdapter.getItem(position);
                    if (!item.isAttention()) {
                        mPresenter.attention(mAdapter.getItem(position).getUserId());
                    }
                    view.setVisibility(View.GONE);
                    break;
                case R.id.container_good:
                    if (mAdapter.getItem(position).isPraise()) {
                        mPresenter.cancelPraise((int) mAdapter.getItemId(position));
                    } else {
                        mPresenter.praise((int) mAdapter.getItemId(position));
                    }
                    break;
                case R.id.view_comment:
                    showCommentInput((int) mAdapter.getItemId(position));
                    break;
                case R.id.container_action_more:
                    int dynamicId = (int) mAdapter.getItemId(position);
                    int userId = mAdapter.getItem(position).getUserId();
                    mDynamicEventDialog = DialogUtilsKt.showBottomReportDialog(getContext(), v -> {
                        switch (v.getId()) {
                            //屏蔽帖子
                            case R.id.tv_block_this_content:
                                mPresenter.blockUserOrDynamic(dynamicId, true, false);
                                mDynamicEventDialog.cancel();
                                break;
                            //屏蔽用户
                            case R.id.tv_block_this_user:
                                // BlockCardOrUserRequest requestUser = new BlockCardOrUserRequest(cardUserId, 2);
                                //assert mPresenter != null;
                                // mPresenter.requestBlockUserOrCard(requestUser);
                                mPresenter.blockUserOrDynamic(userId, true, true);
                                mDynamicEventDialog.dismiss();
                                break;
                            //举报
                            case R.id.tv_report_this_user:
                                mDynamicEventDialog.dismiss();
                                //start(ReportCardFragment.newInstance(dynamicId));
                                ARouter.getInstance().build(ARouterUrlKt.SocialCircleUrl)
                                        .withString("FRAGMENT_KEY", ReportCardFragment.REPORT_PAGE)
                                        .withSerializable("dynamicResult", mAdapter.getItem(position))
                                        .navigation();
                                break;
                            case R.id.tv_delete:
                                //    mPresenter.delSocialCard(mCardId);
                                mPresenter.delDynamic(dynamicId);
                                mDynamicEventDialog.dismiss();
                                break;
                        }
                    }, userId == getApp().getUserInfo().getId());
                    break;
            }
        });
    }

    void refreshData() {
        page = 1;
        loadData(true);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (isNeedRefresh) {
            refreshData();
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    protected void initDataSupport() {
        super.initDataSupport();
        //isNeedRefresh = true;
        //loadData(true);
    }

    private void loadData(boolean isRefresh) {
        DynamicListParams params = new DynamicListParams();
        params.setTopicId(topicId);
        if (flag == 1) {
            params.setIsHot(1);
        }
        /*if (isRefresh) {
            //params.setStartId(0);
           // page = 1;
        } else {
            // params.setStartId((int) mAdapter.getLastItemId());
        }*/
        params.setPage(page);
        params.setPageSize(pageSize);
        mPresenter.fetchTopicDynamic(params);
    }

    private void showCommentInput(int dynamicId) {
        commentDynamicId = dynamicId;
        if (commentDialog == null) {
            commentDialog = new BottomSheetDialog(Objects.requireNonNull(getContext()), R.style.BottomSheetEdit);
            commentDialog.setContentView(R.layout.dialog_comment_bottom_sheet);
            etCommentInput = commentDialog.findViewById(R.id.et_social_circle_reply_comment);
            Button btnComment = commentDialog.findViewById(R.id.btn_comment_send);
            assert etCommentInput != null;
            etCommentInput.setOnEditorActionListener((v, actionId, event) -> {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    String content = etCommentInput.getText().toString().trim();
                    if (StringUtils.isEmpty(content)) {
                        showMessage("内容不能为空");
                        return true;
                    }
                    commentDynamic(commentDynamicId, content);
                    commentDialog.cancel();
                }
                return false;
            });

            if (btnComment != null) {
                btnComment.setOnClickListener(v -> {
                    String content = etCommentInput.getText().toString().trim();
                    if (StringUtils.isEmpty(content)) {
                        showMessage("内容不能为空");
                        return;
                    }
                    commentDynamic(commentDynamicId, content);
                    commentDialog.cancel();
                });
            }

            commentDialog.setOnCancelListener(dialog -> {
                KeyboardUtils.hideSoftInput(recyclerView);
            });
        }
        etCommentInput.setFocusable(true);
        etCommentInput.setFocusableInTouchMode(true);
        etCommentInput.requestFocus();
        commentDialog.show();
        KeyboardUtils.showSoftInput(recyclerView);
    }

    private void commentDynamic(int dynamicId, String commentContent) {
        CommentParams params = new CommentParams();
        params.setDynamicId(dynamicId);
        params.setCommentContent(commentContent);
        mPresenter.comment(params);
    }


    @Override
    public void onFetchDynamic(List<DynamicResult> results) {
        if (isLoadingMore) {
            isLoadingMore = false;
            mAdapter.addData(results);
            if (results.size() < pageSize) {
                isEnd = true;
                //refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                isEnd = false;
                // refreshLayout.finishLoadMore();
            }
        } else {
            mAdapter.setList(results);
            // refreshLayout.finishRefresh();
        }
    }

    @Override
    public void onGetDynamic(DynamicResult result) {

    }

    @Override
    public void onGetComment(List<CommentResult> results, boolean isChild) {

    }

    @Override
    public void onCommentResult(int id, CommentParams params) {

        //updateComment(id, params);
        Map<String, Object> map = new HashMap<>();
        map.put("commentId", id);
        map.put("commentParams", params);
        EventBus.getDefault().post(new HomeEvent(HomeEvent.POST_COMMENT, map, (int) mAdapter.getItemId(eventPos)));
    }

    public void updateComment(int eventPos, int id, CommentParams params) {
        if (etCommentInput != null) {
            etCommentInput.setText("");
        }
        CommentResult commentResult = new CommentResult();
        commentResult.setId(id);
        commentResult.setDynamicId(params.getDynamicId());
        commentResult.setCommentContent(params.getCommentContent());
        commentResult.setNickname(getApp().getUserInfo().getNickName());
        commentResult.setFromUid(getApp().getUserInfo().getId());
        mAdapter.postComment(eventPos, commentResult);
    }

    @Override
    public void onReplyResult(int parentPos, int id, CommentReplyParams params) {

    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        switch (taskId) {
            case DynamicPresenter.PRAISE:
                //mAdapter.postLike(true, eventPos);
                EventBus.getDefault().post(new HomeEvent(HomeEvent.POST_LIKE, (int) mAdapter.getItemId(eventPos)));
                eventPos = -1;
                break;
            case DynamicPresenter.PRAISE_CANCEL:
                // mAdapter.postLike(false, eventPos);
                EventBus.getDefault().post(new HomeEvent(HomeEvent.POST_LIKE_CANCEL, (int) mAdapter.getItemId(eventPos)));
                eventPos = -1;
                break;
            case DynamicPresenter.BLOCK:
                //  mAdapter.blockDynamic((int) mAdapter.getItemId(eventPos));
                EventBus.getDefault().post(new HomeEvent(HomeEvent.DYNAMIC_BLOCK, (int) mAdapter.getItemId(eventPos)));
                eventPos = -1;
                break;
            case DynamicPresenter.BLOCK_USER:
                //      refreshData();
                // mAdapter.blockUser(mAdapter.getItem(eventPos).getUserId());
                EventBus.getDefault().post(new HomeEvent(HomeEvent.USER_BLOCK, (int) mAdapter.getItemId(eventPos)));
                eventPos = -1;
                break;
            case DynamicPresenter.DELETE:
                //  mAdapter.removeAt(eventPos);
                EventBus.getDefault().post(new HomeEvent(HomeEvent.DYNAMIC_DELETE, (int) mAdapter.getItemId(eventPos)));
                eventPos = -1;
                break;
            case DynamicPresenter.ATTENTION:
                // mAdapter.postAttention(eventPos, true);
                EventBus.getDefault().post(new HomeEvent(HomeEvent.POST_ATTENTION, mAdapter.getItem(eventPos).getUserId()));
                break;
        }
    }

    @Subscribe
    public void onHomeEvent(HomeEvent event) {
        int eventPos = mAdapter.getPositionById(event.getDynamicId());

        switch (event.getEvent()) {
            case HomeEvent.DYNAMIC_PUBLISH:
            case HomeEvent.USER_BLOCK:
                isNeedRefresh = true;
                refreshData();
                break;
            case HomeEvent.DYNAMIC_BLOCK:
            case HomeEvent.DYNAMIC_DELETE:
                if (eventPos > -1 && mAdapter != null) {
                    mAdapter.removeAt(eventPos);
                }
                break;
            case HomeEvent.POST_LIKE:
                if (eventPos > -1) {
                    mAdapter.postLike(true, eventPos);
                }
                break;
            case HomeEvent.POST_LIKE_CANCEL:
                if (eventPos > -1) {
                    mAdapter.postLike(false, eventPos);
                }
                break;
            case HomeEvent.POST_COMMENT:
                if (eventPos > -1) {
                    Map<String, Object> commentMap = (Map<String, Object>) event.getObj();
                    int commentId = (int) commentMap.get("commentId");
                    CommentParams commentParams = (CommentParams) commentMap.get("commentParams");
                    updateComment(eventPos, commentId, commentParams);
                }
                break;
            case HomeEvent.DELETE_COMMENT:
                if (eventPos < 0) {
                    return;
                }
                List<CommentResult> commentResults = (List<CommentResult>) event.getObj();
                if (commentResults != null && mAdapter != null) {
                    mAdapter.setNewCommentData(eventPos, commentResults);
                }
                break;
            case HomeEvent.UPDATE_POSITION:
                DynamicResult dynamicResult = (DynamicResult) event.getObj();
                if (dynamicResult != null) {
                    mAdapter.setData(eventPos, dynamicResult);
                }
                break;

            case HomeEvent.POST_ATTENTION:
                LogUtils.d("event------------------>" + GsonUtils.toJson(event));
                mAdapter.postAttentionByUserId((Integer) event.getObj(), true);
                break;
            case HomeEvent.POST_ATTENTION_CANCEL:
                LogUtils.d("event------------------>" + GsonUtils.toJson(event));
                mAdapter.postAttentionByUserId((Integer) event.getObj(), false);
                break;
        }
    }
}
